package service;

import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.jms.TextMessage;
import newspaper.VnexpressImage;
import newspaper.VnexpressThreadManager;

public class VnexpressImageReceiver implements ServletContextListener,
		MessageListener, ExceptionListener {

	@Override
	public void onException(JMSException arg0) {
		throw new UnsupportedOperationException("Not supported yet.");

	}

	@Override
	public void onMessage(Message message) {		
		try {
			TextMessage textMessage = (TextMessage) message;
			String imageName = textMessage.getText().replace(
					"http://vnexpress.net", "");
			imageName = "source" + imageName.replaceAll("/", "-").toLowerCase();
			VnexpressImage imgThread = new VnexpressImage(
					textMessage.getText(), imageName);			
			VnexpressThreadManager.listImageThread.add(imgThread);
			imgThread.start();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		System.out.println(", get ok !");
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		throw new UnsupportedOperationException("Not supported yet.");

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		throw new UnsupportedOperationException("Not supported yet.");

	}

	public void getMessage() throws JMSException, InterruptedException {
		ActiveMQService.setUp("imageSMS");
		MessageConsumer consumer = ActiveMQService.session
				.createConsumer(ActiveMQService.destination);
		ActiveMQService.connection.setExceptionListener(this);
		consumer.setMessageListener(this);
	}
}
